package com.hyfrogx.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hyfrogx.common.form.PageVo;

import java.util.Map;

/**
 * todo 查询参数(分页)
 *
 * @author crazypenguin
 * @version 1.0
 * @created 2018/4/17
 */
public class QueryExt<T> extends Page<T> {
	public static final String PAGE = "page";
	public static final String LIMIT = "limit";
	public static final String ORDER_BY_FIELD = "orderByField";
	public static final String IS_ASC = "isAsc";

	private Map condition;

	public QueryExt(Map<String, Object> params) {
		super(Integer.parseInt(params.getOrDefault(PAGE, 1).toString())
				, Integer.parseInt(params.getOrDefault(LIMIT, 10).toString()));

		String orderByField = params.getOrDefault(ORDER_BY_FIELD, "").toString();
		Boolean isAsc = Boolean.parseBoolean(params.getOrDefault(IS_ASC, Boolean.TRUE).toString());
		if (StringUtils.isNotEmpty(orderByField)) {
			OrderItem orderItem = null;
			if (isAsc) {
				orderItem = OrderItem.asc(orderByField);
			} else {
				orderItem = OrderItem.desc(orderByField);
			}
			this.addOrder(orderItem);
		}

		params.remove(PAGE);
		params.remove(LIMIT);
		params.remove(ORDER_BY_FIELD);
		params.remove(IS_ASC);
		this.setCondition(params);
	}

	public Map getCondition() {
		return condition;
	}

	public void setCondition(Map condition) {
		this.condition = condition;
	}

	public QueryExt(PageVo vo) {
		super();
		if (ObjectUtil.isNotNull(vo)) {
			this.setCurrent(Convert.toInt(vo.getPage(), 1));
			this.setSize(Convert.toInt(vo.getLimit(), 10));
			String orderByField = Convert.toStr(vo.getOrderByField(), "");
			Boolean isAsc = Convert.toBool(vo.getIsAsc(), Boolean.TRUE);
			if (StringUtils.isNotEmpty(orderByField)) {
				OrderItem orderItem = null;
				if (isAsc) {
					orderItem = OrderItem.asc(orderByField);
				} else {
					orderItem = OrderItem.desc(orderByField);
				}
				this.addOrder(orderItem);
			}
			Map params = BeanUtil.beanToMap(vo, false, true);
			params.remove(PAGE);
			params.remove(LIMIT);
			params.remove(ORDER_BY_FIELD);
			params.remove(IS_ASC);
			this.setCondition(params);
		} else {
			this.setCurrent(1);
			this.setSize(10);
		}
	}
}
